{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "\"\"\"\n",
    "加载数据文件，sales_data.csv文件，按照以下要求分析数据\n",
    "- 生成折线图：不同产品的月销售额趋势\n",
    "- 生成柱状图：不同产品的总销售额对比\n",
    "- 生成饼图：不同产品的销售额占比\n",
    "\"\"\""
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 加载csv文件 pandas库 数据分析  安装   pip  install pandas\n",
    "import pandas as pd\n",
    "\n",
    "def load_data(file_path):\n",
    "    # 调用pd中的read_csv函数 将指定文件中的数据加载成一个DataFrame对象\n",
    "    df = pd.read_csv(file_path)\n",
    "    df['Date'] = pd.to_datetime(df['Date'])  # 将字符串类型的日期转换成 datetime类型便于后续的分组处理\n",
    "    return df\n",
    "\n",
    "\n",
    "load_data('sales_data.csv')"
   ],
   "id": "4743f9842351c2c4",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "#生成折线图：不同产品的月销售额趋势\n",
    "\"\"\"\n",
    "    1. 不同产品 每个月  销售额求和     A  1 ->1000  2->1500     B 1  2\n",
    "    2. 整理数据格式  符合折线图的数据格式要求\n",
    "    3. 创建折线图实例  \n",
    "    4. 添加数据\n",
    "    5. 渲染\n",
    "\"\"\"\n",
    "from pyecharts.charts import  Line\n",
    "from pyecharts.globals import ThemeType\n",
    "from pyecharts import options as opts\n",
    "# 参数表示DataFrame类型的数据\n",
    "def generate_line(df):\n",
    "    # 根据产品类型和月份分组  获取Sales列 并求和     reset_index()  重置索引\n",
    "    month_product_sales = df.groupby([df['Date'].dt.to_period('M'),'Product'])['Sales'].sum().reset_index()\n",
    "    # 为了便于x轴日期格式的展示  将Date列转换为str\n",
    "    month_product_sales['Date'] = month_product_sales['Date'].astype('str')\n",
    "    # 创建折线图对象\n",
    "    line = Line(init_opts={'theme': ThemeType.LIGHT})\n",
    "    line.set_global_opts(\n",
    "        title_opts=opts.TitleOpts(\n",
    "            title='不同产品的月销售额趋势'\n",
    "        ),\n",
    "        xaxis_opts=opts.AxisOpts(\n",
    "            axislabel_opts=opts.LabelOpts(\n",
    "                rotate=45,   # 旋转标签\n",
    "            )\n",
    "        ),\n",
    "        toolbox_opts=opts.ToolboxOpts(\n",
    "            is_show=True  # 显示工具箱\n",
    "        )\n",
    "    )\n",
    "    # 处理数据格式  满足折线图要求  x ->[2024-01,2024-02,2024-03...,2024-12]   \n",
    "    x_axis = month_product_sales['Date'].unique().tolist()\n",
    "    line.add_xaxis(x_axis)\n",
    "    # Y轴数据   y -> A [1,2,3...,12]  B [1,2,3,4...12] ...   \n",
    "    for item in month_product_sales['Product'].unique():\n",
    "        #  month_product_sales['Product']==item  ->  [True,False,.....]  \n",
    "        y_data_list = month_product_sales[month_product_sales['Product']==item]['Sales'].tolist()   # [42042,38835,....]\n",
    "        line.add_yaxis(item,y_data_list)\n",
    "    return line\n",
    "generate_line(load_data('sales_data.csv')).render_notebook()"
   ],
   "id": "25c567d71841a480",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "from pyecharts.charts import  Bar\n",
    "# 生成柱状图：不同产品的总销售额对比  年\n",
    "def generate_bar(df):\n",
    "    #  根据商品的类目进行分组求和   年\n",
    "    product_year_sales =  df.groupby(['Product'])['Sales'].sum().reset_index()\n",
    "    # 柱状图 数据格式  [类目列表]  [数值列表]\n",
    "    x_axis = product_year_sales['Product'].tolist()\n",
    "    y_axis = product_year_sales['Sales'].tolist()\n",
    "    # 创建柱状图实例\n",
    "    bar = Bar()\n",
    "    bar.add_xaxis(x_axis)\n",
    "    bar.add_yaxis('年销量', y_axis)\n",
    "    bar.set_global_opts(\n",
    "        title_opts=opts.TitleOpts(\n",
    "            title='不同产品的总销售额对比'\n",
    "        )\n",
    "    )\n",
    "    return bar\n",
    "\n",
    "generate_bar(load_data('sales_data.csv')).render_notebook()\n"
   ],
   "id": "33888fdeabc9f877",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "#生成饼图：不同产品的销售额占比\n",
    "from pyecharts.charts import Pie\n",
    "def generate_pie(df):\n",
    "    #  根据商品的类目进行分组求和   年\n",
    "    product_year_sales =  df.groupby(['Product'])['Sales'].sum().reset_index()\n",
    "    # 饼图数据格式 [['类目',value ],['类目',value],['类目',value]...]\n",
    "    product_list = product_year_sales['Product'].tolist()\n",
    "    sales_list = product_year_sales['Sales'].tolist()\n",
    "    product_sales_tuple_list = list(zip(product_list,sales_list))\n",
    "    result = []\n",
    "    for item in product_sales_tuple_list:\n",
    "        result.append(list(item))\n",
    "    \n",
    "    # 创建饼图对象 \n",
    "    pie = Pie()\n",
    "    pie.set_global_opts(\n",
    "        title_opts=opts.TitleOpts(\n",
    "            title='不同产品的销售额占比'\n",
    "        )\n",
    "    )\n",
    "    pie.add('',result)\n",
    "    return  pie\n",
    "\n",
    "generate_pie(load_data('sales_data.csv')).render_notebook()"
   ],
   "id": "bf384d6cf027d255",
   "outputs": [],
   "execution_count": null
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
